﻿using Core.ApplicationServices;
using Core.DomainServices;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.DomainServices.Hdiphone6wallpaper
{
    public class Hdiphone6wallpaperCrawable : IArticleCrawlable
    {
        private readonly IConfigurable appConfig;
        private readonly HtmlWeb htmlWeb;

        public Hdiphone6wallpaperCrawable(IConfigurable appConfig)
        {
            this.appConfig = appConfig;
            htmlWeb = new HtmlWeb();
        }

        public override bool Parser(string category, IList<string> results)
        {
            string url = BuildUrl(category);
            
            var doc = htmlWeb.Load(url);
            var nodes = doc.DocumentNode.SelectNodes("//div[@class=\"entry \"]");
            if (nodes == null || nodes.Count == 0) return true;
            if (nodes != null && nodes.Count > 0)
            {
                foreach (var node in nodes)
                {
                    var html = node.InnerHtml;
                    var iDoc = new HtmlDocument();
                    iDoc.LoadHtml(html);
                    var item = iDoc.DocumentNode.SelectSingleNode("//a[@class=\"opacity\"]/img");
                    if (item != null)
                    {
                        string href = item.Attributes["src"].Value;
                        if (!results.Contains(href)) results.Add(href);
                        Console.WriteLine(ItemIndex + "=>" + href);
                    }
                    ItemIndex++;
                }
            }

            string keyConfig = GetConfigKeyByUrlAndCategory(RootUrl, category);
            appConfig.AddNewOrUpdateSetting(keyConfig);
            return false;
        }

        public override string BuildUrl(string category)
        {
            string keyConfig = GetConfigKeyByUrlAndCategory(RootUrl, category);
            return string.Format(RootUrl, category, appConfig.GetNextPage(keyConfig));
        }

        public override string RootUrl
        {
            get { return @"http://www.hdiphone6wallpaper.com/category/{0}/page/{1}"; }
        }
    }
}
